﻿using InfonavaEye.model;
using System;
using System.Collections.Generic;
using System.Linq;
using InfonavaEye.components;
using Newtonsoft.Json;
using InfonavaEye.util;
using System.Windows.Forms;
using InfonavaEye.model.wjapi;
using System.Runtime.InteropServices.ComTypes;
using System.Windows.Forms.VisualStyles;

namespace InfonavaEye.Service
{
    /// <summary>
    /// 数据上报服务-通用
    /// </summary>
    public class CommonReportService : IReportService
    {

     static HttpTools httpTools = new HttpTools();
        /// <summary>
        /// 过滤这个服务，满足条件的才可以使用这个服务
        /// </summary>
        /// <param name="upperCode">上位机编码</param>
        /// <returns></returns>
        public bool filter(string upperCode)
        {
            return true;
        }
        /// <summary>
        /// 上报钉盒扫描识别结果
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public void Report(ReportDTO dto)
        {
            ReportData report = new ReportData()
            {
                DeviceNo = Eps.Ai.Common.Config.UPPER_DEVICE_NO,
                data = dto.OcrResults.Select(ocrResult =>
                {
                    var nail = ocrResult.nail;
                    NailPosition nailPoint = null;
                    if (nail != null)
                    {
                        nailPoint = new NailPosition()
                        {
                            Segment = nail.area.code,
                            Row = nail.point.Y,
                            Column = nail.point.X,
                        };
                    }
                    return new ReportNailInfo()
                    {
                        BoxTemplateCode = dto.BoxModel.boxCode,
                        NailPosition = nailPoint,
                        LaserCode = ocrResult.code,
                        ScanImgUrl = null,
                    };
                }).ToList()
            };

            ServiceResult<String> result = this.httpReq<string>(JsonConvert.SerializeObject(report), 
                Eps.Ai.Common.Config.SERIVE_REPPORT_URL, "POST");
            if (result.isSuccess())
            {
                AutoCloseMessageBox.Show("上报成功");
            }
        }

        public CheckResult checkOrder<CheckResult>(ReportDTO dto,String orderNumber) {
            ReportData report = new ReportData()
            {
                DeviceNo = Eps.Ai.Common.Config.UPPER_DEVICE_NO,
                OrderNO = orderNumber,
                data = dto.OcrResults.Select(ocrResult =>
                {
                    var nail = ocrResult.nail;
                    NailPosition nailPoint = null;
                    if (nail != null)
                    {
                        nailPoint = new NailPosition()
                        {
                            Segment = nail.area.code,
                            Row = nail.point.Y,
                            Column = nail.point.X,
                        };
                    }
                    return new ReportNailInfo()
                    {
                        BoxTemplateCode = dto.BoxModel.boxCode,
                        NailPosition = nailPoint,
                        LaserCode = ocrResult.code,
                        ScanImgUrl = null,
                    };
                }).ToList()
            };

            ServiceResult<CheckResult> result = this.httpReq<CheckResult>(JsonConvert.SerializeObject(report),
                Eps.Ai.Common.Config.SERIVE_CHECKITEM_URL, "POST");
           
            return result.data;
        }


        public  Boolean submitCheckReceiptResult(SubmitCheckDataDTO dataDTO)
        {
            if (dataDTO==null) {
                dataDTO = new SubmitCheckDataDTO();
            }
            dataDTO.DeviceNo = Eps.Ai.Common.Config.UPPER_DEVICE_NO;
           
            ServiceResult<string> result = this.httpReq<string>(JsonConvert.SerializeObject(dataDTO),
                Eps.Ai.Common.Config.SERIVE_SUBMINT_RECEIPT_URL, "POST");
            if (result.isSuccess())
            {
                return true;
            }
            return false;


        }

        public List<OrderListRespDto> pullOrderList(string orderType) {
            ServiceResult<List<OrderListRespDto>> result = this.httpReq<List<OrderListRespDto>>(null,
              Eps.Ai.Common.Config.SERIVE_PULL_ORDER_URL+"?order_type="+ orderType, "GET");
            if (result.isSuccess())
            {
                return result.data;
            }
            return null;
        }


        public StorageConfig getAliyunOSSConfig()
        {
           ServiceResult<StorageConfig> result = this.httpReq<StorageConfig>(null,
           Eps.Ai.Common.Config.OCR_SERVICE_DOMAIN + "/api/ocr/getOSSConfig?appKeySecret=00A5BC68C0IU9", "GET");
            if (result.isSuccess())
            {
                return result.data;
            }
            return null;
        }



        public Boolean sendStraightReq(StraightenReqParams dataDTO)
        {
            dataDTO.DeviceNo = Eps.Ai.Common.Config.UPPER_DEVICE_NO;
            ServiceResult<string> result = this.httpReq<string>(JsonConvert.SerializeObject(dataDTO),
                Eps.Ai.Common.Config.OCR_SERVICE_DOMAIN+ "/api/ocr/straighten", "POST");
            if (result.isSuccess())
            {
                return true;
            }
            return false;


        }

        public List<OCRServerResult> queryOCRResult(string captureOptSN)
        {
            OCRCommonResult<List<OCRServerResult>> result = this.ocrHttpCommonReq<List<OCRServerResult>> ( null,
                Eps.Ai.Common.Config.OCR_SERVICE_DOMAIN + "/api/ocr/queryResutl?scanSN="+ captureOptSN, "GET");
            if (result.isSuccess())
            {
                return result.data;
            }
            return null;


        }
        private ServiceResult<T> httpReq<T>(String jsonData, String url, string type)
        {
            try
            {
                /* var res = new HttpClientHelper().PostJSON(
                                 url, jsonData, 3000);
                HttpTools httpTools= new HttpTools();*/
                var res = "";
                if ("POST".Equals(type)) {
                     res = HttpTools.getInstance().HTTPJsonPost(url, jsonData);
                }
                if ("GET".Equals(type))
                {
                    res = HttpTools.getInstance().HTTPJsonGet(url);
                }
              Console.WriteLine("服务器接口响应参数：{0}",res);
                if (string.IsNullOrEmpty(res))
                {
                    AutoCloseMessageBox.Show("服务器请求失败，返回数据为空");
                    ServiceResult<T> resultNullError = new ServiceResult<T> {
                        code = 500,
                        msg = "服务器请求失败，返回数据为空",
                    };
                    return resultNullError;
                }
                ServiceResult<T> result = JsonConvert.DeserializeObject<ServiceResult<T>>(res);
                if (!result.isSuccess())
                {
                    MessageBox.Show(result.msg);
                    Console.WriteLine("发生错误，返回：{0}", result.msg);
                }
                return result;
            }catch (Exception ex)
            {
                MessageBox.Show("服务器请求异常，" + ex.Message);
                Console.WriteLine("上报失败，异常：{0}", ex);
            }
            ServiceResult<T> resultError = new ServiceResult<T>
            {
                code = 500,
                msg = "服务器请求失败，发生异常",
            };
            return resultError;
        }

        private int netErrorCount = 0;
        private OCRCommonResult<T> ocrHttpCommonReq<T>(String jsonData, String url, string type)
        {
            try
            {
                /* var res = new HttpClientHelper().PostJSON(
                                 url, jsonData, 3000);
                HttpTools httpTools= new HttpTools();*/
                var res = "";
                if ("POST".Equals(type))
                {
                    res = httpTools.HTTPJsonPost(url, jsonData);
                }
                if ("GET".Equals(type))
                {
                    res = httpTools.HTTPJsonGet(url);
                }
                Console.WriteLine("服务器接口响应参数：{0}", res);
                netErrorCount = 0;
                if (string.IsNullOrEmpty(res))
                {
                    AutoCloseMessageBox.Show("服务器请求失败，返回数据为空");
                    OCRCommonResult<T> resultNullError = new OCRCommonResult<T>
                    {
                        code = 500,
                        msg = "服务器请求失败，返回数据为空",
                    };
                    return resultNullError;
                }
                OCRCommonResult<T> result = JsonConvert.DeserializeObject<OCRCommonResult<T>>(res);
                if (!result.isSuccess())
                {
                    MessageBox.Show(result.msg);
                    Console.WriteLine("发生错误，返回：{0}", result.msg);
                }
                return result;
            }
            catch (Exception ex)
            {
                netErrorCount = netErrorCount + 1;
                if (netErrorCount>=3) {
                    MessageBox.Show("服务器请求异常，" + ex.Message);
                    Console.WriteLine("上报失败，异常：{0}", ex);
                }
            }
            OCRCommonResult<T> resultError = new OCRCommonResult<T>
            {
                code = 500,
                msg = "服务器请求失败，发生异常",
            };
            return resultError;
        }
        public bool cleanOCRResult(string captureOptSN)
        {
            OCRCommonResult<bool> result = this.ocrHttpCommonReq<bool>(null,
                   Eps.Ai.Common.Config.OCR_SERVICE_DOMAIN + "/api/ocr/cleanOcr?scanSN=" + captureOptSN, "GET");
            if (result.isSuccess())
            {
                return result.data;
            }
            return false;
        }
    }

  
}
